package com.sgai.zero_robot.ui.select_file_config;

import android.content.Context;
import android.net.Uri;
import com.sgai.zero_robot.ui.history.RunnableCallBack;
import com.sgai.zero_robot.utils.LogUtil;
import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ReadXLSRunnable implements Runnable {
    private final RunnableCallBack<List<TowerDetail>> callBack;
    private final Uri uri;
    private final Context context;

    public ReadXLSRunnable(Context context,Uri uri, RunnableCallBack<List<TowerDetail>> callBack){
        this.callBack=callBack;
        this.uri=uri;
        this.context=context;
    }
    @Override
    public void run() {
        XSSFWorkbook workbook;
        List<TowerDetail> list = new ArrayList<>();
        try {
            try {
                InputStream is = context.getContentResolver().openInputStream(uri);
                workbook = new XSSFWorkbook(is); // try xlsx
            } catch (NotOfficeXmlFileException e) {
                // not xlsx, try xls: reopen InputStream as needed
                LogUtil.i("EXCEL", "Not xlsx, try xls: " + e.getMessage());
                        // Caller should re-open input stream and call parseExcelInputStreamForXls with that stream
                return;
            }
            Sheet sheet = workbook.getSheetAt(0); // first sheet
            int rowCount = sheet.getPhysicalNumberOfRows();
            if (rowCount<=1){
                if (callBack!=null){
                    callBack.onResult(list);
                }
                return;
            }
            LogUtil.i("EXCEL", "Sheet name=" + sheet.getSheetName() + ", rows=" + rowCount);
            for (int i =1;i<rowCount;i++){
                Row row = sheet.getRow(i);
                int last = row.getLastCellNum();
                if (last<4){
                    continue;
                }
                TowerDetail towerDetail = new TowerDetail();
                towerDetail. lineName = row.getCell(0).getStringCellValue();
                towerDetail. towerNum = ((int) row.getCell(1).getNumericCellValue());
                towerDetail. province = row.getCell(2).getStringCellValue();
                towerDetail. city = row.getCell(3).getStringCellValue();
                list.add(towerDetail);
            }
            workbook.close();
        } catch (Exception ex) {
            LogUtil.e(ex,Thread.currentThread());
        }finally {
            if (callBack!=null){
                callBack.onResult(list);
            }
        }
    }
}